<template>
  <div>
    <h3>新增待办事项</h3>
    <input
      type="text" 
      v-model="todoName"
      placeholder="输入待办事项名称"
      @keydown.enter="addTodo(newTodo(todoName))">
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { key } from '../store'
import type { Todo } from '../types'

const todoName = ref('')
const store = useStore(key)
const router = useRouter()
const todos = computed(() => store.state.todos?.todos)

const newTodo = (todoName: string): Todo => {
  return {
    id: todos.value?.length + 1,
    name: todoName,
    completed: false
  }
}

const addTodo = (todo: Todo): void => {
  store.commit('todos/addTodo', todo)
  todoName.value = ''
  // 跳转会列表页面
  router.push({ path: '/' })
}
</script>

<style>

</style>